package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.common.util.CheckPhoneUtil;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    public boolean checkPhone(String phone) throws LogicException {
        //检验手机号码是否符合格式
        boolean ret = CheckPhoneUtil.isMobile(phone);
        if (!ret) {
            throw new LogicException("手机号码格式不正确");
        }
        int rets = userInfoMapper.selectCountByPhone(phone);
        //ret > 0 说明已被注册  返回true
        return rets > 0;
    }

    //必须抛出去,否则统一找不到LogicException  只会找到范围更大的
    public void sendVerifyCode(String phone) throws LogicException {
        //检验手机号码是否符合格式
        boolean ret = CheckPhoneUtil.isMobile(phone);
        if (!ret) {
            throw new LogicException("手机号码格式不正确");
        }

        String time = userInfoRedisService.getDate(phone);
        if (time != null) {
            //说明缓存了
            long nowTime = new Date().getTime();
            long redTime = Long.valueOf(time);
            long abs = Math.abs((nowTime - redTime) / 1000);
            if (abs < 60) {
                //说明不超过五分钟,告知用户
                throw new LogicException("请不要频繁操作,一分钟后再重新申请验证码");
            }
        }


        //发送验证码
        StringBuilder sb = new StringBuilder();
        //uuid随机生成四位数的验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        //模拟发送验证码到对方手机中  具体查看项目二
        sb.append("您的验证码是:").append(code).append(",请在" + Consts.VERIFY_CODE_VAI_TIME + "分钟内使用");
        System.out.println(sb);
        //将验证码保存到redis中
        userInfoRedisService.setVerifyCode(phone, code);
        //保存的时候,保存现在的时间,反正用户重复发送验证码
        userInfoRedisService.setDate(phone, new Date());
    }

    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws LogicException {
        //1.检验参数是否为空
        AssertUtil.hasLength(phone, "手机号码不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "确认密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        //2.校验二次密码是否一致
        AssertUtil.isEquals(password, rpassword, "两次密码不一致");
        //3.校验手机号码的格式是否符合规则
        //检验手机号码是否符合格式
        boolean ret = CheckPhoneUtil.isMobile(phone);
        if (!ret) {
            throw new LogicException("手机号码格式不正确");
        }
        //4.校验验证码
        String code = userInfoRedisService.getVerifyCode(phone);
        if (code == null) {
            //说明已经失效
            throw new LogicException("验证码已失效");
        }
        //忽略大小写
        if (!code.equalsIgnoreCase(verifyCode)) {
            //说明验证码不匹配
            throw new LogicException("验证码不匹配");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setLevel(1);
        userInfo.setNickname(nickname);
        //注意  密码还需要进行加密
        userInfo.setPassword(password);
        userInfo.setPhone(phone);
        userInfo.setState(UserInfo.STATE_NORMAL);
        //都成功了,那么保存数据
        userInfoMapper.insert(userInfo);
    }

    public String userLogin(String username, String password) throws LogicException {
        //数据的非空判断
        AssertUtil.hasLength(username, "用户名不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        UserInfo user = userInfoMapper.selectByUsernameAndPassword(username, password);
        if (user == null) {
            //说明该用户不存在
            throw new LogicException("该用户不存在");
        }
        //如果用户存在  创建token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //将token作为key,user的json对象作为value  存入Redis中
        userInfoRedisService.setUserInfo(token, JSON.toJSONString(user));
        return token;
    }

    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }
}
